package com.itheima.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mapper.UmsRoleMenuRelationMapper;
import com.itheima.pojo.UmsRoleMenuRelation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UmsRoleMenuRelationImpl implements UmsRoleMenuRelationApi {
    @Autowired
    private UmsRoleMenuRelationMapper mapper;

    @Override
    public List<Long> getRoleMenuIds(List<Long> adminRoleId) {
        List<UmsRoleMenuRelation> umsRoleMenuRelations
                = mapper.selectList(new LambdaQueryWrapper<UmsRoleMenuRelation>().in(UmsRoleMenuRelation::getRoleId, adminRoleId));
        List<Long> menuIds = CollUtil.getFieldValues(umsRoleMenuRelations, "menuId", Long.class);

        return menuIds;
    }

    //给角色分配菜单
    @Override
    public void allocMenu(ArrayList<Integer> menuIds, Integer roleId) {

        LambdaQueryWrapper<UmsRoleMenuRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRoleMenuRelation::getRoleId, roleId);
        List<UmsRoleMenuRelation> umsRoleMenuRelations = mapper.selectList(lqw);

        //1.首先判断传入的menuIds是否为空
        if (menuIds.size() == 0) {
            //如果为空,查询数据库是否有数据
            if (umsRoleMenuRelations.size() == 0) {
                //数据库也没有数据的话直接结束;
                return;
            } else {
                //如果数据库有数据,将数据库的数据清除
                mapper.delete(lqw);
            }
            //2.如果传入的ids不为空,查看数据库是否有数据
        } else {

            if (umsRoleMenuRelations.size() == 0) {
                //数据库没有数据的话直接保存;
                for (Integer menuId : menuIds) {
                    UmsRoleMenuRelation rmr = new UmsRoleMenuRelation();
                    rmr.setMenuId(Long.valueOf(menuId));
                    rmr.setRoleId(Long.valueOf(roleId));
                    mapper.insert(rmr);
                }
            } else {
                //如果数据库有数据,将数据库的数据原来的数据清除保存新的数据
                mapper.delete(lqw);

                for (Integer menuId : menuIds) {
                    UmsRoleMenuRelation rmr = new UmsRoleMenuRelation();
                    rmr.setMenuId(Long.valueOf(menuId));
                    rmr.setRoleId(Long.valueOf(roleId));
                    mapper.insert(rmr);
                }
            }
        }
    }

    //获取角色相关菜单
    @Override
    public List<UmsRoleMenuRelation> listRmr(Integer roleId) {

        LambdaQueryWrapper<UmsRoleMenuRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRoleMenuRelation::getRoleId, roleId);
        List<UmsRoleMenuRelation> umsRoleMenuRelations = mapper.selectList(lqw);

        return umsRoleMenuRelations;

    }


}
